<template>
  <div class="board-detail-page">
    <div class="container">
      <!-- 加载状态 -->
      <div v-if="loading" class="loading-container">
        <el-skeleton :rows="10" animated />
      </div>

      <!-- 内容区 -->
      <div v-else>
        <!-- 板块信息 -->
        <div class="board-info-card">
          <div class="board-header">
            <div class="board-icon" :style="{ backgroundColor: board.color }">
              <el-icon><component :is="board.icon" /></el-icon>
            </div>
            <div class="board-title">
              <h1>{{ board.name }}</h1>
              <div class="board-meta">
                
                <div class="meta-item">
                  <el-icon><chat-dot-round /></el-icon>
                  <span>{{ board.postCount }}个帖子</span>
                </div>
                <div class="meta-item">
                  <el-icon><user /></el-icon>
                  <span>版主：{{ board.moderator }}</span>
                </div>
              </div>
            </div>
            <div class="board-actions">
              <el-button type="primary" @click="createTopic">
                <el-icon><plus /></el-icon>在本版发帖
              </el-button>
            </div>
          </div>
          <div class="board-description">
            {{ board.description }}
          </div>
        </div>

        <!-- 话题列表 -->
        <div class="topics-container">
          <div class="filter-bar">
            <div class="filter-tabs">
              <el-radio-group v-model="filter" size="large">
                <el-radio-button label="all">全部话题</el-radio-button>
                <el-radio-button label="hot">热门</el-radio-button>
                <el-radio-button label="essence">精华</el-radio-button>
              </el-radio-group>
            </div>
            <div class="search-box">
              <el-input
                v-model="searchKeyword"
                placeholder="搜索本版话题"
                @keyup.enter="searchTopics"
                clearable
              >
                <template #suffix>
                  <el-icon class="search-icon" @click="searchTopics"><search /></el-icon>
                </template>
              </el-input>
            </div>
          </div>

          <!-- 话题列表 -->
          <div class="topic-list" v-if="topics.length > 0">
            <div 
              v-for="topic in topics" 
              :key="topic.id" 
              class="topic-card"
              @click="viewTopic(topic.id)"
            >
              <div class="topic-content">
                <div class="topic-tags" v-if="topic.isTop || topic.isEssence">
                  <span v-if="topic.isTop" class="tag top">置顶</span>
                  <span v-if="topic.isEssence" class="tag essence">精华</span>
                </div>
                <h3 class="topic-title">{{ topic.title }}</h3>
                <div class="topic-excerpt">{{ topic.excerpt }}</div>
                <div class="topic-meta">
                  <div class="meta-item">
                    <el-icon><view /></el-icon>
                    <span>{{ topic.views }}次浏览</span>
                  </div>
                  <div class="meta-item">
                    <el-icon><chat-line-round /></el-icon>
                    <span>{{ topic.replies }}条回复</span>
                  </div>
                  <div class="meta-item">
                    <el-icon><star /></el-icon>
                    <span>{{ topic.votes }}人赞</span>
                  </div>
                </div>
              </div>
              
              <div class="topic-info">
                <div class="author-avatar">
                  <img v-if="topic.author && topic.author.avatar" :src="getFullAvatarURL(topic.author.avatar)" :alt="topic.author.name">
                  <div class="avatar-placeholder" v-else>{{ topic.author && topic.author.name ? topic.author.name.substring(0, 1) : '?' }}</div>
                </div>
                <div class="topic-time">
                  <div class="author-name">{{ topic.author ? topic.author.name : '未知用户' }}</div>
                  <div class="publish-time">{{ topic.publishTime || '未知时间' }}</div>
                </div>
              </div>
            </div>
          </div>
          
          <!-- 空状态 -->
          <div v-else class="empty-state">
            <el-empty description="暂无话题" :image-size="200">
              <template #description>
                <p>该板块下暂无话题，赶快发表第一个话题吧！</p>
              </template>
              <el-button type="primary" @click="createTopic">发表话题</el-button>
            </el-empty>
          </div>
          
          <!-- 分页 -->
          <div class="pagination-container" v-if="topics.length > 0">
            <el-pagination
              background
              layout="prev, pager, next"
              :total="total"
              :page-size="pageSize"
              :current-page="currentPage"
              @current-change="handlePageChange"
            />
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { 
  Plus, 
  ChatRound, 
  ChatDotRound, 
  User,
  View,
  ChatLineRound,
  Search,
  Star,
  Briefcase,
  Coin,
  School,
  Reading,
  OfficeBuilding,
  Guide
} from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getBoardDetail } from '@/api/forum'
import { formatDistanceToNow } from 'date-fns'
import { zhCN } from 'date-fns/locale'
import { getFullAvatarURL } from '@/utils/common'

const route = useRoute()
const router = useRouter()
const loading = ref(true)

// 板块ID
const boardId = ref(parseInt(route.params.id))

// 板块信息
const board = reactive({
  id: 0,
  name: '',
  description: '',
  icon: '',
  color: '',
  moderator: '',
  topicCount: 0,
  postCount: 0
})

// 话题列表
const topics = ref([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)
const filter = ref('all')
const searchKeyword = ref('')

// 监听路由参数变化
watch(() => route.params.id, (newId) => {
  boardId.value = parseInt(newId)
  fetchBoardData()
})

// 获取板块数据
const fetchBoardData = async () => {
  console.log(`[DEBUG] 开始获取板块数据，板块ID: ${boardId.value}, 页码: ${currentPage.value}, 过滤器: ${filter.value}`)
  loading.value = true
  try {
    // 添加一个时间戳参数，强制刷新而不使用缓存
    const timestamp = new Date().getTime();
    const res = await getBoardDetail(boardId.value, {
      page: currentPage.value,
      size: pageSize.value,
      filter: filter.value,
      keyword: searchKeyword.value,
      _t: timestamp // 添加时间戳防止缓存
    })
    
    console.log(`[DEBUG] 板块数据响应:`, res)
    
    if (res.code === 200) {
      // 设置板块信息
      Object.assign(board, res.data.board)
      
      // 设置图标
      const iconMapping = {
        'briefcase': 'Briefcase',
        'coin': 'Coin',
        'school': 'School',
        'reading': 'Reading',
        'office-building': 'OfficeBuilding',
        'guide': 'Guide'
      }
      board.icon = iconMapping[board.icon] || 'Briefcase'
      
      // 设置话题列表
      if (res.data.topics && Array.isArray(res.data.topics)) {
        console.log('[DEBUG] 找到话题数据，数量:', res.data.topics.length)
        console.log('[DEBUG] 话题ID列表:', res.data.topics.map(t => t.id).join(', '))
        
        topics.value = res.data.topics.map(topic => {
          // 确保topic对象有有效的author属性
          if (!topic.author) {
            topic.author = {
              name: '未知用户',
              avatar: null
            }
          } else if (!topic.author.name && topic.author.username) {
            // 数据中使用username字段，而不是name字段
            topic.author.name = topic.author.username
          } else if (!topic.author.name) {
            topic.author.name = '未知用户'
          }
          
          // 添加摘要文本
          if (topic.content && !topic.excerpt) {
            // 去除HTML标签
            const textContent = topic.content.replace(/<[^>]+>/g, '')
            // 截取前100个字符作为摘要
            topic.excerpt = textContent.substring(0, 100) + (textContent.length > 100 ? '...' : '')
          } else if (!topic.excerpt) {
            topic.excerpt = '暂无内容'
          }
          
          return {
            ...topic,
            publishTime: formatTime(topic.createTime)
          }
        })
        
        // 设置分页信息
        total.value = res.data.total || res.data.topics.length || 0
      } else {
        // 如果没有话题数据，设置为空数组
        topics.value = []
        total.value = 0
        console.log('[DEBUG] 没有找到话题数据或格式不正确', res.data)
      }
    }
  } catch (error) {
    console.error('[DEBUG] 获取板块数据失败', error)
    console.error('[DEBUG] 错误响应:', error.response ? error.response.data : '无响应数据')
    ElMessage.error('获取板块数据失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

// 格式化时间
const formatTime = (timestamp) => {
  if (!timestamp) return ''
  try {
    return formatDistanceToNow(new Date(timestamp), { addSuffix: true, locale: zhCN })
  } catch (error) {
    console.error('时间格式化错误', error)
    return ''
  }
}

// 在本版发帖
const createTopic = () => {
  // 检查用户是否登录
  const token = localStorage.getItem('token')
  if (!token) {
    router.push({
      path: '/auth/login',
      query: { redirect: `/forum/create?boardId=${boardId.value}` }
    })
    return
  }
  
  router.push({
    path: '/forum/create',
    query: { boardId: boardId.value }
  })
}

// 查看话题详情
const viewTopic = (topicId) => {
  router.push(`/forum/topics/${topicId}`)
}

// 处理分页变化
const handlePageChange = (page) => {
  currentPage.value = page
  fetchBoardData()
}

// 搜索话题
const searchTopics = () => {
  currentPage.value = 1
  fetchBoardData()
}

// 监听筛选条件变化
watch(filter, () => {
  currentPage.value = 1
  fetchBoardData()
})

onMounted(() => {
  fetchBoardData()
})
</script>

<style lang="scss" scoped>
@import '@/assets/styles/variables.css';

@mixin multi-line-ellipsis($lines) {
  display: -webkit-box;
  -webkit-line-clamp: $lines;
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
}

.board-detail-page {
  padding: var(--spacing-xl) 0;
  background-color: var(--bg-light);
  min-height: calc(100vh - 60px);
}

.container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 var(--spacing-lg);
}

// 加载状态
.loading-container {
  padding: var(--spacing-xl);
  background-color: white;
  border-radius: var(--border-radius);
  box-shadow: var(--box-shadow-sm);
}

// 板块信息卡片
.board-info-card {
  background-color: white;
  border-radius: var(--border-radius);
  padding: var(--spacing-lg);
  box-shadow: var(--box-shadow-sm);
  margin-bottom: var(--spacing-lg);
  
  .board-header {
    display: flex;
    align-items: center;
    margin-bottom: var(--spacing-md);
    
    .board-icon {
      display: flex;
      align-items: center;
      justify-content: center;
      width: 60px;
      height: 60px;
      border-radius: 12px;
      margin-right: var(--spacing-md);
      
      .el-icon {
        font-size: 30px;
        color: white;
      }
    }
    
    .board-title {
      flex-grow: 1;
      
      h1 {
        font-size: 1.8rem;
        font-weight: 700;
        margin: 0 0 var(--spacing-xs);
        color: var(--text-primary);
      }
      
      .board-meta {
        display: flex;
        gap: var(--spacing-lg);
        
        .meta-item {
          display: flex;
          align-items: center;
          font-size: 0.9rem;
          color: var(--text-secondary);
          
          .el-icon {
            margin-right: var(--spacing-xs);
            color: var(--color-primary);
          }
        }
      }
    }
  }
  
  .board-description {
    font-size: 1rem;
    color: var(--text-secondary);
    line-height: 1.6;
  }
}

// 话题列表
.topics-container {
  background-color: white;
  border-radius: var(--border-radius);
  padding: var(--spacing-lg);
  box-shadow: var(--box-shadow-sm);
  
  .filter-bar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: var(--spacing-lg);
    
    .search-box {
      max-width: 300px;
      
      .search-icon {
        cursor: pointer;
        color: var(--color-primary);
      }
    }
  }
  
  .topic-list {
    display: flex;
    flex-direction: column;
    gap: var(--spacing-md);
    
    .topic-card {
      display: flex;
      border: 1px solid var(--border-color);
      border-radius: var(--border-radius);
      padding: var(--spacing-md);
      transition: all 0.3s;
      cursor: pointer;
      
      &:hover {
        transform: translateY(-3px);
        box-shadow: var(--box-shadow-md);
        border-color: var(--color-primary);
      }
      
      .topic-content {
        flex-grow: 1;
        
        .topic-tags {
          display: flex;
          gap: var(--spacing-xs);
          margin-bottom: var(--spacing-xs);
          
          .tag {
            padding: 2px 6px;
            border-radius: 4px;
            font-size: 0.8rem;
            font-weight: 500;
            
            &.top {
              background-color: var(--color-danger-light);
              color: var(--color-danger);
            }
            
            &.essence {
              background-color: var(--color-success-light);
              color: var(--color-success);
            }
          }
        }
        
        .topic-title {
          font-size: 1.2rem;
          font-weight: 600;
          margin: 0 0 var(--spacing-xs);
          color: var(--text-primary);
        }
        
        .topic-excerpt {
          font-size: 0.95rem;
          color: var(--text-secondary);
          margin-bottom: var(--spacing-sm);
          @include multi-line-ellipsis(2);
        }
        
        .topic-meta {
          display: flex;
          flex-wrap: wrap;
          align-items: center;
          gap: var(--spacing-md);
          
          .meta-item {
            display: flex;
            align-items: center;
            font-size: 0.85rem;
            color: var(--text-light);
            
            .el-icon {
              margin-right: var(--spacing-xs);
              font-size: 0.95rem;
            }
          }
        }
      }
      
      .topic-info {
        display: flex;
        flex-direction: column;
        align-items: center;
        margin-left: var(--spacing-md);
        min-width: 120px;
        
        .author-avatar {
          width: 50px;
          height: 50px;
          border-radius: 50%;
          overflow: hidden;
          margin-bottom: var(--spacing-sm);
          
          img {
            width: 100%;
            height: 100%;
            object-fit: cover;
          }
          
          .avatar-placeholder {
            width: 100%;
            height: 100%;
            display: flex;
            align-items: center;
            justify-content: center;
            background-color: var(--color-primary);
            color: white;
            font-size: 1.5rem;
            font-weight: 500;
          }
        }
        
        .topic-time {
          text-align: center;
          
          .author-name {
            font-size: 0.9rem;
            font-weight: 500;
            margin-bottom: 4px;
            color: var(--text-primary);
          }
          
          .publish-time {
            font-size: 0.8rem;
            color: var(--text-light);
          }
        }
      }
    }
  }
  
  .empty-state {
    padding: var(--spacing-xl) 0;
  }
  
  .pagination-container {
    display: flex;
    justify-content: center;
    margin-top: var(--spacing-lg);
  }
}

// 响应式调整
@media (max-width: 768px) {
  .board-info-card {
    .board-header {
      flex-direction: column;
      align-items: flex-start;
      
      .board-icon {
        margin-bottom: var(--spacing-sm);
      }
      
      .board-title {
        margin-bottom: var(--spacing-md);
        
        .board-meta {
          flex-wrap: wrap;
          gap: var(--spacing-md);
        }
      }
    }
  }
  
  .topics-container {
    .filter-bar {
      flex-direction: column;
      align-items: stretch;
      gap: var(--spacing-md);
      
      .search-box {
        max-width: 100%;
      }
    }
    
    .topic-list {
      .topic-card {
        flex-direction: column;
        
        .topic-info {
          flex-direction: row;
          justify-content: flex-start;
          margin-left: 0;
          margin-top: var(--spacing-sm);
          padding-top: var(--spacing-sm);
          border-top: 1px solid var(--border-color);
          width: 100%;
          
          .author-avatar {
            margin-bottom: 0;
            margin-right: var(--spacing-sm);
          }
          
          .topic-time {
            text-align: left;
          }
        }
      }
    }
  }
}
</style> 